package com.ljl.rest;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.Acknowledgment;
import org.springframework.kafka.support.SendResult;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author 刘家良
 * @date 2022/10/29 19:17
 * @description /
 */
@RestController
public class KafkaController {

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    @KafkaListener(topics = "myTopic", groupId = "group1")
    public void group1(String msg) {
        System.out.printf("group1收到消息[%s]\r\n", msg);
    }

    @KafkaListener(topics = "myTopic", groupId = "group2")
    public void group2(String msg) {
        System.out.printf("group2收到消息[%s]\r\n", msg);
    }

    @RequestMapping("/send/{msg}")
    public void sendMsg(@PathVariable(name = "msg")String msg) {
        ListenableFuture<SendResult<String, String>> send1 = kafkaTemplate.send("myTopic", msg);
        send1.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
            @Override
            public void onFailure(Throwable ex) {
                System.out.println("myTopic -> msg1 发送消息失败");
            }

            @Override
            public void onSuccess(SendResult<String, String> result) {
                System.out.println("myTopic -> msg1 发送消息成功");
            }
        });
    }

}
